package com.link.base.base.serviceprojectnew.controller;

import com.link.base.base.approval.exception.ApprovalNeedUserException;
import com.link.base.base.serviceprojectnew.model.Project;
import com.link.base.base.serviceprojectnew.model.ProjectTeam;
import com.link.base.base.serviceprojectnew.model.PublishProgram;
import com.link.base.base.serviceprojectnew.model.ServiceProject;
import com.link.base.user.model.CoreUser;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.util.UserUtil;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.util.StringUtils;
import com.link.base.base.serviceprojectnew.service.ProjectTeamService;
import com.link.base.base.serviceprojectnew.service.PublishProgramService;
import com.link.base.base.serviceprojectnew.service.ServiceProjectService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author unknown
 * @date unknown
 * @comments 发布程序审核
 */
@Controller
@RequestMapping("/link/publishProgram")
public class PublishProgramController extends BasicController<PublishProgram> {

    @Resource
    private KeyGenerateService keyGenerateService;

    @Resource
    private PublishProgramService publishProgramService;
    @Resource
    private ProjectTeamService projectTeamService;
    @Resource
    private ServiceProjectService serviceProjectService;

    private static final Pattern PATTERN = Pattern.compile("(?<=\\[)([^\\(^\\)]+?)(?=\\])");

    @Override
    public BasicService<PublishProgram> getBasicService() throws Exception {
        return publishProgramService;
    }

    @RequestMapping(value = "/PublishProgramSubmit", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> publishProgramSubmit(@JsonParam PublishProgram record,@JsonParam  String selectUserId, HttpSession session,
                                                    HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            publishProgramService.submitPublishProgram(record, Long.parseLong(selectUserId));
            result.put("success", true);
        } catch (ApprovalNeedUserException e) {
            LCLogger.withException(e);
//            Pattern pattern = Pattern.compile("(?<=\\[)([^\\(^\\)]+?)(?=\\])");
            Matcher match = PATTERN.matcher(e.getMessage());
            List<String> filedList = new ArrayList<String>();
            while (match.find()) {
                filedList.add(match.group());
            }
            result.put("success", false);
            result.put("mustSelectUser", true);
            result.put("userId", filedList.get(0));
            result.put("nodeId", filedList.get(1));
            result.put("result", "必须选择用户！");
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/initNew")
    @ResponseBody
    public Map<String, Object> initNew(@JsonParam QueryParams qps, HttpSession session, HttpServletRequest request,
                                       HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            PublishProgram publishProgram = new PublishProgram();
            publishProgram.setId(keyGenerateService.keyGenerate());
            // 用于页面显示
            publishProgram.setAuditStatus("待审批");
            // 用于页面显示
            publishProgram.setPublishStatus("未发布");
            publishProgram.setOriginator(user.getFirstName());
            // 标记
            publishProgram.setRow_status("NEW");
            result.put("success", true);
            result.put("result", publishProgram);
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/selectDevelopersList")
    @ResponseBody
    public Map<String, Object> queryDevelopersList(@JsonParam QueryParams qps, HttpSession session, HttpServletRequest request,
                                                   HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.preDealSecurity(request);
            PublishProgram t = new PublishProgram();
            String projName = request.getParameter("project");
            String developers = request.getParameter("developers");
            t.setProject(projName);
            String[] developerArr = null;
            if (!StringUtils.isNull(developers)) {
                developerArr = developers.split(",");
                t.setRows(t.getRows() + developerArr.length);
            }
            Project project = new Project();
            List<ProjectTeam> list = projectTeamService.queryPublishDevelopersListPage(project);
            //去除已经选择的开发人员
            if (developerArr != null) {
                List<ProjectTeam> ptList = new ArrayList<ProjectTeam>();
                for (ProjectTeam projectTeam : list) {
                    boolean flag = false;
                    for (String name : developerArr) {
                        if (projectTeam.getFirstName() != null && projectTeam.getFirstName().equals(name.trim())) {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag) {
                        ptList.add(projectTeam);
                    }
                }
                list = ptList;
            }

            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    @RequestMapping(value = "/selectRelatedTasksList")
    @ResponseBody
    public Map<String, Object> queryRelatedTasksList(@JsonParam QueryParams qps, HttpSession session, HttpServletRequest request,
                                                     HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.preDealSecurity(request);
            CoreUser user = UserUtil.getUser();
            ServiceProject t = new ServiceProject();
            t.setLoginCorpId(user.getLoginCorpId());
            String projName = request.getParameter("project");
            String relatedTasks = request.getParameter("relatedTasks");
            System.err.println(relatedTasks);
            String[] relatedTaskArr = null;
            if (!StringUtils.isNull(relatedTasks)) {
                //%%%作为各个任务之间的分隔符
                relatedTaskArr = relatedTasks.split("%%%");
                t.setRows(t.getRows() + relatedTaskArr.length);
            }
            t.setProjName(projName);
            List<ServiceProject> list = serviceProjectService.queryPublishTasksList(t);
            //不重复显示已选任务
            if (relatedTaskArr != null) {
                List<ServiceProject> spList = new ArrayList<ServiceProject>();
                for (ServiceProject serviceProject : list) {
                    boolean flag = false;
                    for (String task : relatedTaskArr) {
                        if (serviceProject.getAbstracts() != null
                                && serviceProject.getAbstracts().equals(task.substring(task.indexOf('-') + 1).trim())) {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag) {
                        spList.add(serviceProject);
                    }
                }
                list = spList;
            }

            result.put("success", true);
            result.put("rows", list);
            result.put("total", list.size());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/updatePublishStatus")
    @ResponseBody
    public Map<String, Object> updatePublishStatus(@JsonParam PublishProgram record, HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Long rowId = record.getId();
            if (null == rowId) {
                result.put("success", false);
                result.put("result", "ID不能为空");
                return result;
            }
            record.setPublishStatus("Published");
            publishProgramService.updatePublishStatus(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @Override
    public void beforUpsert(PublishProgram record, HttpServletRequest request) {
        if (StringUtils.isNull(record.getName())) {
            throw new ServiceException("SERVICEREQUEST-006");
        }
        if (StringUtils.isNull(record.getType())) {
            throw new ServiceException("SERVICEREQUEST-007");
        }
        if (StringUtils.isNull(record.getProject())) {
            throw new ServiceException("SERVICEREQUEST-008");
        }
    }
}
